package com.gupt.reggie.controller;/*
@author name
@data 2023/4/22-16:37
*/

import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gupt.reggie.common.BaseContext;
import com.gupt.reggie.common.R;
import com.gupt.reggie.entity.User;
import com.gupt.reggie.service.UserService;
import com.gupt.reggie.utils.ValidateCodeUtils;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 发送手机验证码
     * @param session
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(HttpSession session, @RequestBody User user){
        //接收前端的验证码
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();//生成4位数的验证码

            log.info("验证码为：{}",code);

            //调用阿里云的短信服务api
 //           SMSUtils.sendMessage("阿里云服务签名","密钥",phone,code);

            //验证码存入session
//            session.setAttribute(phone,code);

            //使用redis将验证码缓存，有效期5min
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            return R.success("手机验证码发送成功");
        }
        return R.error("验证码接收异常");
    }

    @PostMapping("/login")
    public R<User> login(HttpSession session, @RequestBody  Map map){  //用map也能接收前端的json数据

        String code = map.get("code").toString();

        String phone = map.get("phone").toString();
        
        //获取后端生成的验证码
//        Object codeInSession = session.getAttribute(phone);

        //从redis中获取验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);

        //验证码校验
        if(codeInSession != null && code.equals(codeInSession)){
            //登录成功
            //用手机号判断是否为新用户，不是则默认加入用户表
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();

            queryWrapper.eq(User::getPhone,phone);
            //查询该手机号的用户
            User user = userService.getOne(queryWrapper);

            if(user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //用户id存入session，方便过滤器判断用户是否登录
            session.setAttribute("user",user.getId());

            //登录成功，删除redis缓存的验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("验证码错误，请重试");
    }

    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){
        session.removeAttribute("user");
        BaseContext.removeCurrentId();
        return R.success("退出登录成功");
    }
}
